package com.tanhua.server.service;

import cn.hutool.cache.CacheUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.UploadPicService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.UploadPicResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class VideoService {
    @Autowired
    private UploadPicService uploadPicService;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    private QuanZiService quanZiService;

    @Autowired
    private UserInfoService userInfoService;
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    public Boolean saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        User user = UserThreadLocal.get();
        Video video = new Video();
        video.setUserId(user.getId());
        video.setSeeType(1); //默认公开
        try {
            //上传封面图片
            UploadPicResult uploadPicResult = uploadPicService.uploadPic(picFile);
            video.setPicUrl(uploadPicResult.getName());
            //上传视频
            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(),
                    videoFile.getSize(),
                    StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true),
                    null);
            //设置视频url
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
            String videoId = videoApi.saveVideo(video);
            return StrUtil.isNotEmpty(videoId);
        } catch (IOException e) {
            log.error("发布小视频失败！file = " + picFile.getOriginalFilename(), e);
        }
        return false;
    }

    public PageResult queryVideoList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Video> pageInfo = videoApi.queryVideoList(user.getId(), page, pageSize);
        List<Video> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        //查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(userIds);
        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video record : records) {
            VideoVo videoVo = new VideoVo();
            videoVo.setUserId(record.getUserId());
            videoVo.setCover(record.getPicUrl());
            videoVo.setVideoUrl(record.getVideoUrl());
            videoVo.setId(record.getId().toHexString());
            videoVo.setSignature("我就是我~"); //TODO 签名

            videoVo.setCommentCount(0); //TODO 评论数
            videoVo.setHasFocus(0); //TODO 是否关注
            videoVo.setHasLiked(this.quanZiApi.queryCommentType(videoVo.getId(), user.getId()) ? 1 : 0); //是否点赞（1是，0否）
            videoVo.setLikeCount(Convert.toInt(this.quanZiApi.queryRedisLikes(videoVo.getId())));//点赞数


            //填充用户信息
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equal(userInfo.getUserId(), videoVo.getUserId())) {
                    videoVo.setAvatar(userInfo.getLogo());
                    videoVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            videoVoList.add(videoVo);
        }
        pageResult.setItems(videoVoList);
        return pageResult;
    }

    /**
     * 点赞
     *
     * @param videoId
     * @return
     */
    public Long likeComment(String videoId) {
        Long likeCount = null;
        try {
            User user = UserThreadLocal.get();
            boolean isLiked = quanZiApi.queryCommentType(videoId, user.getId());
            if (isLiked) {
                return null;
            }
            likeCount = Long.valueOf(quanZiApi.saveLiked(videoId, user.getId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return likeCount;
    }

    public Long disLikeComment(String videoId) {
        Long likeCount = null;
        try {
            User user = UserThreadLocal.get();
            boolean isLiked = quanZiApi.queryCommentType(videoId, user.getId());
            if (!isLiked) {
                return null;
            }
            likeCount = Long.valueOf(quanZiApi.deleteLiked(videoId, user.getId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return likeCount;
    }

    public Boolean followUser(Long userId) {
        User user = UserThreadLocal.get();
        return videoApi.followUser(user.getId(), userId);
    }

    public Boolean disFollowUser(Long userId) {
        User user = UserThreadLocal.get();
        return videoApi.disFollowUser(user.getId(), userId);
    }
}
